// import request from '@/utils/request'
import { request } from '@/utils/request'  // 改为命名导入
import { cacheService } from './cacheService'

// 添加网络请求错误处理包装函数
const safeRequest = async (url, config = {}) => {
  try {
    const response = await request(url, config);
    return response;
  } catch (error) {
    console.error(`请求失败 (${url}):`, error);
    // 添加一些重试逻辑或者错误处理
    if (error.response) {
      console.error('服务器响应状态:', error.response.status);
      console.error('服务器响应数据:', error.response.data);
    } else if (error.request) {
      console.error('未收到响应，请检查网络连接');
    } else {
      console.error('请求配置错误:', error.message);
    }
    throw error;
  }
};

// 预加载数据
export async function preloadData() {
  const preloadQueue = cacheService.getPreloadQueue()
  if (preloadQueue.length === 0) return

  const promises = preloadQueue.map(async (key) => {
    const [type, param] = key.split('_')
    try {
      const data = await fetchDataByType(type, param)
      cacheService.set(key, data)
      cacheService.removeFromPreloadQueue(key)
    } catch (error) {
      console.error(`预加载数据失败: ${key}`, error)
    }
  })

  await Promise.all(promises)
}

// 根据类型获取数据
async function fetchDataByType(type, param = '', signal) {
  try {
    let response;
    switch(type) {
      case 'trade':
        response = await safeRequest('/statistics/tradeStatistics', { 
          params: { timeRange: param },
          signal
        });
        return response;
      case 'member':
        response = await safeRequest('/statistics/memberStatistics', { 
          params: { timeRange: param },
          signal
        });
        return response;
      case 'region':
        response = await safeRequest('/statistics/regionStatistics', { 
          params: { 
            region: param,
            includeDetails: true // 请求包含详细数据
          },
          signal
        });
        return response;
      case 'good':
        response = await safeRequest('/statistics/goodStatistics', { 
          params: { timeRange: param },
          signal
        });
        return response;
      case 'order':
        response = await safeRequest('/statistics/orderStatistics', { 
          params: { timeRange: param },
          signal
        });
        return response;
      case 'coupon':
        response = await safeRequest('/statistics/couponStatistics', { 
          params: { timeRange: param },
          signal
        });
        return response;
      case 'quick':
        response = await safeRequest('/statistics/integralStatistics', { signal });
        return response;
      case 'income_expense':
        response = await safeRequest('/statistics/incomeExpenseStatistics', { signal });
        return response;
      case 'merchant_penetration':
        response = await safeRequest('/statistics/merchantPenetrationStatistics', { signal });
        return response;
      case 'user_penetration':
        response = await safeRequest('/statistics/userPenetrationStatistics', { signal });
        return response;
      case 'merchant_ranking':
        response = await safeRequest('/statistics/merchantRankingStatistics', { signal });
        return response;
      case 'consumer_ranking':
        response = await safeRequest('/statistics/consumerRankingStatistics', { signal });
        return response;
      default:
        throw new Error(`未知的数据类型: ${type}`)
    }
  } catch (error) {
    console.error(`获取数据失败: ${error}`);
    // 返回模拟数据
    return {
      data: getMockDataByType(type, param)
    }
  }
}

// 获取模拟数据
function getMockDataByType(type, param = '') {
  const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  const regions = ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '西安', '南京', '重庆']
  const categories = ['食品', '家电', '服装', '日用品', '其他']
  const merchants = ['优质商家A', '优质商家B', '优质商家C', '优质商家D', '优质商家E']
  const consumers = ['活跃用户A', '活跃用户B', '活跃用户C', '活跃用户D', '活跃用户E']
  
  switch(type) {
    case 'trade':
      return {
        values: Array(12).fill(0).map(() => Math.floor(Math.random() * 1000 + 100)),
        labels: months
      }
    case 'member':
      return {
        values: Array(12).fill(0).map(() => Math.floor(Math.random() * 500 + 50)),
        labels: months
      }
    case 'region':
      return {
        regions: regions.map(name => ({
          name,
          value: Math.floor(Math.random() * 100)
        })),
        trade: {
          values: Array(12).fill(0).map(() => Math.floor(Math.random() * 1000 + 100)),
          labels: months
        },
        member: {
          values: Array(12).fill(0).map(() => Math.floor(Math.random() * 500 + 50)),
          labels: months
        },
        good: {
          categories: categories.map(name => ({
            name,
            value: Math.floor(Math.random() * 100)
          }))
        },
        order: {
          values: Array(12).fill(0).map(() => Math.floor(Math.random() * 800 + 200)),
          labels: months
        },
        coupon: {
          values: Array(12).fill(0).map(() => Math.floor(Math.random() * 300 + 50)),
          labels: months
        }
      }
    case 'good':
      return {
        categories: categories.map(name => ({
          name,
          value: Math.floor(Math.random() * 100)
        }))
      }
    case 'order':
      return {
        values: Array(12).fill(0).map(() => Math.floor(Math.random() * 800 + 200)),
        labels: months
      }
    case 'coupon':
      return {
        values: Array(12).fill(0).map(() => Math.floor(Math.random() * 300 + 50)),
        labels: months
      }
    case 'quick':
      return {
        orderCount: Math.floor(Math.random() * 100 + 50),
        memberCount: Math.floor(Math.random() * 50 + 20),
        goodCount: Math.floor(Math.random() * 30 + 10)
      }
    case 'income_expense':
      return {
        totalIncome: Math.floor(Math.random() * 10000 + 5000),
        totalExpense: Math.floor(Math.random() * 5000 + 2000)
      }
    case 'merchant_penetration':
      return {
        regions: regions.slice(0, 5).map(name => ({
          name,
          value: Math.floor(Math.random() * 100)
        }))
      }
    case 'user_penetration':
      return {
        regions: regions.slice(0, 5).map(name => ({
          name,
          value: Math.floor(Math.random() * 100)
        }))
      }
    case 'merchant_ranking':
      return {
        names: merchants,
        values: merchants.map(() => Math.floor(Math.random() * 50000 + 10000))
      }
    case 'consumer_ranking':
      return {
        names: consumers,
        values: consumers.map(() => Math.floor(Math.random() * 10000 + 1000))
      }
    default:
      return {}
  }
}

// 获取交易统计
export async function getTradeStatistics(timeRange = 0) {
  const cacheKey = `trade_${timeRange}`
  if (cacheService.has(cacheKey)) {
    return cacheService.get(cacheKey)
  }
  cacheService.addToPreloadQueue(cacheKey)
  const response = await fetchDataByType('trade', timeRange)
  if (response && response.data) {
    cacheService.set(cacheKey, response.data)
    return response.data
  }
  return { values: [] }
}

// 获取会员统计
export async function getMemberStatistics(timeRange = 0) {
  const cacheKey = `member_${timeRange}`
  if (cacheService.has(cacheKey)) {
    return cacheService.get(cacheKey)
  }
  cacheService.addToPreloadQueue(cacheKey)
  const response = await fetchDataByType('member', timeRange)
  if (response && response.data) {
    cacheService.set(cacheKey, response.data)
    return response.data
  }
  return { values: [] }
}

// 获取地区分布
export async function getRegionStatistics(region = '') {
  const cacheKey = `region_${region}`
  if (cacheService.has(cacheKey)) {
    return cacheService.get(cacheKey)
  }
  cacheService.addToPreloadQueue(cacheKey)
  const response = await fetchDataByType('region', region)
  if (response && response.data) {
    cacheService.set(cacheKey, response.data)
    return response.data
  }
  return { regions: [] }
}

// 获取商品统计
export async function getGoodStatistics(timeRange = 0) {
  const cacheKey = `good_${timeRange}`
  if (cacheService.has(cacheKey)) {
    return cacheService.get(cacheKey)
  }
  cacheService.addToPreloadQueue(cacheKey)
  const response = await fetchDataByType('good', timeRange)
  if (response && response.data) {
    cacheService.set(cacheKey, response.data)
    return response.data
  }
  return { categories: [] }
}

// 获取订单统计
export async function getOrderStatistics(timeRange = 0) {
  const cacheKey = `order_${timeRange}`
  if (cacheService.has(cacheKey)) {
    return cacheService.get(cacheKey)
  }
  cacheService.addToPreloadQueue(cacheKey)
  const response = await fetchDataByType('order', timeRange)
  if (response && response.data) {
    cacheService.set(cacheKey, response.data)
    return response.data
  }
  return { values: [] }
}

// 获取优惠券统计
export async function getCouponStatistics(timeRange = 0) {
  const cacheKey = `coupon_${timeRange}`
  if (cacheService.has(cacheKey)) {
    return cacheService.get(cacheKey)
  }
  cacheService.addToPreloadQueue(cacheKey)
  const response = await fetchDataByType('coupon', timeRange)
  if (response && response.data) {
    cacheService.set(cacheKey, response.data)
    return response.data
  }
  return { values: [] }
}

// 获取快捷统计
export async function getQuickStatistics() {
  const cacheKey = 'quick'
  if (cacheService.has(cacheKey)) {
    return cacheService.get(cacheKey)
  }
  cacheService.addToPreloadQueue(cacheKey)
  const response = await fetchDataByType('quick')
  if (response && response.data) {
    cacheService.set(cacheKey, response.data)
    return response.data
  }
  return { orderCount: 0, memberCount: 0, goodCount: 0 }
}

// 获取收支统计
export async function getIncomeExpenseStatistics() {
  const cacheKey = 'income_expense'
  if (cacheService.has(cacheKey)) {
    return cacheService.get(cacheKey)
  }
  cacheService.addToPreloadQueue(cacheKey)
  const response = await fetchDataByType('income_expense')
  if (response && response.data) {
    cacheService.set(cacheKey, response.data)
    return response.data
  }
  return { totalIncome: 0, totalExpense: 0 }
}

// 获取商家地区渗透率
export async function getMerchantPenetrationStatistics() {
  const cacheKey = 'merchant_penetration'
  if (cacheService.has(cacheKey)) {
    return cacheService.get(cacheKey)
  }
  cacheService.addToPreloadQueue(cacheKey)
  const response = await fetchDataByType('merchant_penetration')
  if (response && response.data) {
    cacheService.set(cacheKey, response.data)
    return response.data
  }
  return { regions: [] }
}

// 获取用户地区渗透率
export async function getUserPenetrationStatistics() {
  const cacheKey = 'user_penetration'
  if (cacheService.has(cacheKey)) {
    return cacheService.get(cacheKey)
  }
  cacheService.addToPreloadQueue(cacheKey)
  const response = await fetchDataByType('user_penetration')
  if (response && response.data) {
    cacheService.set(cacheKey, response.data)
    return response.data
  }
  return { regions: [] }
}

// 获取商家收益排行
export async function getMerchantRankingStatistics() {
  const cacheKey = 'merchant_ranking'
  if (cacheService.has(cacheKey)) {
    return cacheService.get(cacheKey)
  }
  cacheService.addToPreloadQueue(cacheKey)
  const response = await fetchDataByType('merchant_ranking')
  if (response && response.data) {
    cacheService.set(cacheKey, response.data)
    return response.data
  }
  return { names: [], values: [] }
}

// 获取消费者提现排行
export async function getConsumerRankingStatistics() {
  const cacheKey = 'consumer_ranking'
  if (cacheService.has(cacheKey)) {
    return cacheService.get(cacheKey)
  }
  cacheService.addToPreloadQueue(cacheKey)
  const response = await fetchDataByType('consumer_ranking')
  if (response && response.data) {
    cacheService.set(cacheKey, response.data)
    return response.data
  }
  return { names: [], values: [] }
}

// 清除所有缓存
export function clearStatisticsCache() {
  cacheService.clear()
}

// 获取缓存状态
export function getCacheStatus() {
  return cacheService.getStatus()
}

/**
 * 获取商家入驻新闻数据
 * @returns {Promise<Array>} 商家数据列表
 */
export const getMerchantNews = async (signal) => {
  try {
    const response = await safeRequest('/api/statistics/merchant/news', { signal });
    return response.data;
  } catch (error) {
    console.error('获取商家入驻数据失败:', error);
    // 返回默认的模拟数据，避免UI崩溃
    return [
      { name: '优质商家A', time: '2023-10-10 08:30', location: '北京' },
      { name: '优质商家B', time: '2023-10-09 14:25', location: '上海' },
      { name: '优质商家C', time: '2023-10-08 11:15', location: '广州' }
    ];
  }
} 